package com.jenvin.servlet.cookie;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class CookieServlet
 */
public class CookieServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * Default constructor.
	 */
	public CookieServlet() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		//throw new IOException();
		response.setStatus(404);
//		request.getRequestDispatcher("cookietest.jsp").forward(request,
//				response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String action = request.getParameter("action");
		if (action == null) {
			response.setContentType("text/plain");
			PrintWriter writer = response.getWriter();
			writer.write("error action can't be null");
			response.flushBuffer();
			return;
		}
		if ("add".equalsIgnoreCase(action)) {
			String cookieValue = request.getParameter("cookieValue");
			String cookieName = request.getParameter("cookieName");
			String domain = request.getParameter("domain");
			Cookie cookie = new Cookie(cookieName, cookieValue);
			cookie.setDomain(domain);
			cookie.setPath("/");
			cookie.setMaxAge(86400);
			request.setAttribute("cookieName", cookieName);
			request.setAttribute("cookieValue", cookieValue);
			request.setAttribute("domain", domain);
			response.addCookie(cookie);
		}
		if ("remove".equalsIgnoreCase(action)) {
			String cookieName = request.getParameter("cookieName");
			String domain = request.getParameter("domain");
			Cookie cookie = new Cookie(cookieName, "");
			if (domain != null && domain.length() != 0) {
				cookie.setDomain(domain);
			}
			cookie.setPath("/");
			cookie.setMaxAge(0);
			request.setAttribute("cookieName", cookieName);

			request.setAttribute("domain", domain);

			response.addCookie(cookie);
		}
		if ("get".equalsIgnoreCase(action)) {
			Cookie[] cookies = request.getCookies();
			for (Cookie c : cookies) {
				if ("name".equals(c.getName())) {
					System.out.println(c.getName() + "" + c.getValue());
					break;
				}
			}

		}
		request.getRequestDispatcher("cookietest.jsp").forward(request,
				response);
	}

}
